package com.xunwulian.cmpp.pdu;


import com.xunwulian.cmpp.sms.ByteBuffer;
import com.xunwulian.cmpp.sms.ByteData;
import com.xunwulian.cmpp.sms.NotEnoughDataInByteBufferException;
import com.xunwulian.cmpp.sms.PDUException;
import com.xunwulian.cmpp.util.CmppConstant;
import com.xunwulian.cmpp.util.IDGenerator;
import org.codehaus.jackson.annotate.JsonIgnore;

import java.io.Serializable;

public class CmppPDUHeader extends ByteData implements Serializable {

    @JsonIgnore
    private static final long serialVersionUID = 8232040457805693966L;

    /**
     * 消息总长度(含消息头及消息体)
     */
    private int commandLength = CmppConstant.PDU_HEADER_SIZE;

    /**
     * 命令或响应类型
     */
    private int commandId = 0;

    /**
     * 消息流水号,顺序累加,步长为1,循环使用（一对请求和应答消息的流水号必须相同）
     */
    private int sequenceNumber = 0;

    public CmppPDUHeader() {
        sequenceNumber = IDGenerator.incrInt();
    }

    @JsonIgnore
    public ByteBuffer getData() {
        ByteBuffer buffer = new ByteBuffer();
        buffer.appendInt(getCommandLength());
        buffer.appendInt(getCommandId());
        buffer.appendInt(getSequenceNumber());
        return buffer;
    }

    @JsonIgnore
    public void setData(ByteBuffer buffer) throws PDUException {
        try {
            commandLength = buffer.removeInt();
            commandId = buffer.removeInt();
            sequenceNumber = buffer.removeInt();
        } catch (NotEnoughDataInByteBufferException e) {
            throw new PDUException(e);
        }
    }


    public int getCommandLength() {
        return commandLength;
    }

    public void setCommandLength(int commandLength) {
        this.commandLength = commandLength;
    }

    public int getCommandId() {
        return commandId;
    }

    public void setCommandId(int commandId) {
        this.commandId = commandId;
    }

    public int getSequenceNumber() {
        return sequenceNumber;
    }

    public void setSequenceNumber(int sequenceNumber) {
        this.sequenceNumber = sequenceNumber;
    }
}
